import { ClickModal, ClickUpload, useCall, useEffectState, useReq } from '@/components';
import { useSharedWriteObjectMapping, useWriteObjectMapping } from '@/pages/components/hooks/useWriteObject';
import { message, Radio } from 'antd';
import * as PropTypes from 'prop-types';
import React, { forwardRef, useState } from 'react';

SelectFormulaTable = forwardRef(SelectFormulaTable);

function SelectFormulaTable(props, ref) {
  const { relationCode = null, fileType = 'A1', list: listProp, attachment, onOk, ...rest } = props;
  const [state, setState] = useEffectState(attachment);
  const [list, setList] = useEffectState(listProp);
  const [dimensional, setDimension] = useState(attachment?.dimensional || 'two');
  const req = useReq({ url: '/factorPool/upExcel', method: 'POST' });
  const writeObjectMapping = useSharedWriteObjectMapping();

  const onUpload = useCall(async () => {
    const [file] = await ClickUpload.create('.xls,.xlsx,.csv');
    if (!file) return;
    const data = new FormData();
    data.append('fileType', fileType);
    data.append('dimensional', dimensional);
    data.append('file', file);
    const { data: res } = await req.start({ data });
    let { attachment, list } = res?.data || {};
    if (!attachment || !list) {
      message.error(res.msg || res.message || '未知错误');
      return false;
    }
    attachment.dimensional = dimensional;
    setState(attachment);

    list = list.map((factorName, sort) => {
      const factoryObject = writeObjectMapping[factorName];
      const factorCode = factoryObject?.substr(factoryObject?.lastIndexOf(',') + 1);
      return {
        factorName, // 保单年度
        rateType: fileType,
        sort: sort + 1,
        factoryObject, // 保单年度
        factorCode, // 保单年度
      };
    });
    setList(list);

    console.log({ list, attachment });
    onOk?.({ list, attachment });
  });

  const upload = (
    <Radio.Group
      options={[
        { value: 'two', label: '二维' },
        { value: 'three', label: '三维' },
      ]}
      value={dimensional}
      onChange={(e) => setDimension(e.target.value)}
    />
  );

  return <ClickModal width={240} ref={ref} title='Table' {...rest} onOk={onUpload} content={upload} okText='上传' />;
}

SelectFormulaTable.propTypes = {
  relationCode: PropTypes.string,
  fileType: PropTypes.string,
  list: PropTypes.any,
  attachment: PropTypes.any,
  onOk: PropTypes.func,
  onToggle: PropTypes.func,
};

export default SelectFormulaTable;
